using Microsoft.AspNetCore.Mvc;
using RAG.Application.Dtos.Chat;
using RAG.Application.Services.Interfaces;
using System.Security.Claims;

namespace RAG.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class ChatController : ControllerBase
{
    private readonly IRagChatService _ragChatService;

    public ChatController(IRagChatService ragChatService)
    {
        _ragChatService = ragChatService;
    }

    [HttpPost]
    public async Task<ActionResult<ChatResponseDto>> Chat([FromBody] ChatRequestDto request)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(request.Question))
                return BadRequest(new { message = "问题不能为空" });

            var userId = GetCurrentUserId();
            var response = await _ragChatService.ChatAsync(request, userId);

            return Ok(response);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    private Guid GetCurrentUserId()
    {
        var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        if (Guid.TryParse(userIdClaim, out var userId))
            return userId;

        // 临时用于测试，实际应该从JWT Token中获取
        return Guid.Parse("00000000-0000-0000-0000-000000000001");
    }
}
